package com.hd.trans.ui.activity;

import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.hd.trans.R;
import com.hd.trans.TranslationInterior;
import com.hd.trans.camera.CameraConfiguration;
import com.hd.trans.camera.FrameMetadata;
import com.hd.trans.camera.LensEngine;
import com.hd.trans.camera.LensEnginePreview;
import com.hd.trans.common.Constants;
import com.hd.trans.common.interf.VoiceComposeListener;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.LanguageTips;
import com.hd.trans.db.bean.TranslateRecord;
import com.hd.trans.framework.dialog.LanguageDialog;
import com.hd.trans.framework.dialog.LanguageDialogType;
import com.hd.trans.framework.dialog.ShareDialog;
import com.hd.trans.framework.languages.ShareItemBean;
import com.hd.trans.framework.languages.ShareResultAdapter;
import com.hd.trans.framework.tools.AppEvents;
import com.hd.trans.framework.tools.HuDunEvent;
import com.hd.trans.homefun.EventCode;
import com.hd.trans.limit4Use.LimitUseListener;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.network.component.HdTranslateComponent;
import com.hd.trans.network.component.TranslateCallback;
import com.hd.trans.share.EnShareFileType;
import com.hd.trans.share.ShareTextFileManager;
import com.hd.trans.transactor.WordTransactor;
import com.hd.trans.ui.base.LimitBaseActivity;
import com.hd.trans.ui.base.TransInit;
import com.hd.trans.ui.model.HomeTextModel;
import com.hd.trans.utils.CamParaUtil;
import com.hd.trans.utils.CheckDoubleClick;
import com.hd.trans.utils.Constant;
import com.hd.trans.utils.ScreenUtil;
import com.hd.trans.utils.StringUtils;
import com.hd.trans.utils.ToastUtils;
import com.hd.trans.utils.TrackerForTrans;
import com.hd.trans.utils.VoicePlayUtil;
import com.hd.trans.widgets.ImageTextView;
import com.hd.trans.widgets.VoicePlayView;
import com.hd.trans.widgets.views.overlay.GraphicOverlay;
import com.huawei.hms.mlsdk.text.MLText;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Objects;

public class WordTranslateActivity extends LimitBaseActivity {

    private HomeTextModel mDataModel;
    private LanguageDialog languageDialog;
    private boolean isTranslating;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_word_translate;
    }

    private View viewCut;
    private View view1;
    private View view2;
    private View viewLeft;
    private View btnCamera;
    private LensEnginePreview preview;
    private GraphicOverlay graphicOverlay;
    private TextView tvOriginal;
    private TextView tvTrans;
    private LinearLayout llResultPart;
    private LinearLayout llResultNone;
    private TextView tvFrom;
    private TextView tvTo;
    private TextView tvStatusTips1;
    private TextView tvStatusTips2;
    private TextView tvToUse;
    private TextView tvRetry;
    private View rlTransPart;
    private View llDemo;
    private View lyFrom;
    private View lyTo;
    private TextView tvTipsWords;
    private ImageView ivFlashlight;
    private ImageView ivSwitch;
    private ImageTextView ivMenuCollect;
    private ImageTextView copyLayout;
    private ImageTextView shareLayout;

    private static final int DELAY_MS = 3000;//处理帧频率，每隔多少毫秒处理一次
    private static boolean isOpenCollect = true;
    private VoicePlayUtil voicePlayUtil;
    private HdTranslateComponent mTranslateComponent;//  文本翻译组件
    private CameraConfiguration cameraConfiguration;
    private WordTransactor wordTransactor;
    private LensEngine lensEngine;
    private TranslateRecord translateRecord;
    private VoicePlayView mCurrentViewVoice;
    private VoicePlayView viewVoiceFrom;
    private VoicePlayView viewVoiceTo;
    private ShareDialog shareDialog;
    private String codeType;
    private long lastTime;
    private int facing;
    private String originalText;//最后原文
    private String translatedText;//最后翻译文本
    private String lastTransCode;
    private String lastOriginalCode;
    private boolean isDemoShow;
    private boolean isFromPage = true;
    private boolean isLandScape;
    private boolean isAllowPass = true;
    private boolean isInitialization = false;
    private boolean isLocked = false;
    private boolean twoWay;
    private Handler mHandler = new MsgHandler(this);

    @NonNull
    @Override
    public EventCode getPageType() {
        return EventCode.WORD_TRANS;
    }

    private class MsgHandler extends Handler {
        WeakReference<WordTranslateActivity> mMainActivityWeakReference;

        public MsgHandler(WordTranslateActivity mainActivity) {
            this.mMainActivityWeakReference = new WeakReference<>(mainActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            WordTranslateActivity mainActivity = this.mMainActivityWeakReference.get();
            if (mainActivity == null || isDemoShow || isLocked || !isAllowPass) {
                return;
            }
            if (msg.what == Constant.SHOW_TAKE_PHOTO_BUTTON) {
                if(isAllowPass){
                    llResultPart.setVisibility(View.VISIBLE);
                    llResultNone.setVisibility(View.GONE);
                }
            } else if (msg.what == Constant.HIDE_TAKE_PHOTO_BUTTON) {
                isAllowPass = false;
                stopPlaying();
                llResultPart.setVisibility(View.GONE);
                llResultNone.setVisibility(View.VISIBLE);
                if(lensEngine != null){
                    lensEngine.pauseHandlePreviewFrame();
                }
            }
        }
    }

    public static void open(Context context, LimitUseListener listener) {
        setLimitListener(listener);
        Intent intent = new Intent(context, WordTranslateActivity.class);
        context.startActivity(intent);
    }

    public static void open(Context context, LimitUseListener listener,boolean isOpen) {
        setLimitListener(listener);
        isOpenCollect = isOpen;
        Intent intent = new Intent(context, WordTranslateActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        super.initViewsAndEvents(savedInstanceState);

        TranslationInterior.getTrackerListener().view("取词翻译页面");
        if (savedInstanceState != null) {
            this.facing = savedInstanceState.getInt(Constant.CAMERA_FACING);
        }
        this.preview = this.findViewById(R.id.live_preview);
        this.graphicOverlay = this.findViewById(R.id.live_overlay);
        this.cameraConfiguration = new CameraConfiguration();
        this.cameraConfiguration.setPreviewWidth(ScreenUtil.getScreenHeight(this));
        this.cameraConfiguration.setPreviewHeight(ScreenUtil.getScreenWidth(this));
        this.cameraConfiguration.setCameraFacing(this.facing);
        this.cameraConfiguration.setDelayMs(DELAY_MS);
        this.initViews();
        this.isLandScape = (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
        this.createLensEngine();
        this.lensEngine.pauseHandlePreviewFrame();
        this.initTransComponent();
        this.initDataModel();
    }

    private void initDataModel() {
        mDataModel = new ViewModelProvider(this).get(HomeTextModel.class);

        /*
         *  监听页面数据变化(语言改变，翻译状态改变)
         */
        mDataModel.getOperateRecord().observe(this, record -> {
            stopPlaying();
            this.translateRecord = record;

            rlTransPart.setVisibility(View.VISIBLE);
            tvTrans.setText(translatedText);

            //收藏状态
            updateCollectStatus(translateRecord);
        });

        mDataModel.getLanguageFrom().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                tvFrom.setText(huDunLanguage.getName());
                PreferenceMgr.getInstance().getTranslatePreference().saveWorTransCode(huDunLanguage.getTranslateCode());

                restartLensEngine(huDunLanguage.getTranslateCode());

                boolean isSupportedAudioPlay = !huDunLanguage.getTtsCode().isEmpty();
                viewVoiceFrom.setVisibility(isSupportedAudioPlay?View.VISIBLE:View.GONE);
            }
        });
        mDataModel.getLanguageTo().observe(this, huDunLanguage -> {
            if (huDunLanguage != null) {
                tvTo.setText(huDunLanguage.getName());
                updateSwitchStatus(huDunLanguage);

                boolean isSupportedAudioPlay = !huDunLanguage.getTtsCode().isEmpty();
                viewVoiceTo.setVisibility(isSupportedAudioPlay?View.VISIBLE:View.GONE);
            }
        });

        mDataModel.getTranslateState().observe(this, this::translateStateChanged);

        if(DataBaseMgr.getInstance().getDaoSession()==null){
            DataBaseMgr.init(this);
        }

        String fromLangName = PreferenceMgr.getInstance().getTranslatePreference().getWorTransFromLanguage();
        String toLangName = PreferenceMgr.getInstance().getTranslatePreference().getWorTransToLanguage();
        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName));
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName));

        LanguageTips languageTips = TransInit.getLanguageTipsMap().get(fromLangName);
        if(TextUtils.isEmpty(languageTips.getTipsWordsTrans())){
            tvTipsWords.setText(R.string.tips_word_trans);
        }else {
            tvTipsWords.setText(languageTips.getTipsWordsTrans());
        }
    }

    private void initViews() {
        viewCut = findViewById(R.id.view_cut);
        btnCamera = findViewById(R.id.btn_camera);
        view1 = findViewById(R.id.view1);
        view2 = findViewById(R.id.view2);
        viewLeft = findViewById(R.id.view_left);

        llResultPart = findViewById(R.id.ll_result_part);
        llResultNone = findViewById(R.id.ll_result_none);
        llResultPart.setVisibility(View.GONE);//默认隐藏
        llResultNone.setVisibility(View.GONE);//默认隐藏
        tvOriginal = findViewById(R.id.tv_original);
        tvTrans = findViewById(R.id.tv_trans);
        tvFrom = findViewById(R.id.tv_from);
        tvTo = findViewById(R.id.tv_to);
        rlTransPart = findViewById(R.id.rl_trans_part);
        tvStatusTips1 = findViewById(R.id.tv_status_tips1);
        tvStatusTips2 = findViewById(R.id.tv_status_tips2);
        llDemo = findViewById(R.id.ll_demo);
        tvToUse = findViewById(R.id.tv_to_use);
        ivFlashlight = findViewById(R.id.iv_flashlight);
        viewVoiceFrom = findViewById(R.id.view_voice_from);
        viewVoiceTo = findViewById(R.id.view_voice_to);
        ivMenuCollect = findViewById(R.id.iv_menu_collect);
        ivMenuCollect.setVisibility(isOpenCollect?View.VISIBLE:View.GONE);
        copyLayout = findViewById(R.id.copy_layout);
        shareLayout = findViewById(R.id.share_layout);
        tvRetry = findViewById(R.id.tv_retry);
        ivSwitch = findViewById(R.id.iv_switch);
        lyFrom = findViewById(R.id.ly_from);
        lyTo = findViewById(R.id.ly_to);
        tvTipsWords = findViewById(R.id.tv_tips_words);

        lyFrom.setOnClickListener(this);
        lyTo.setOnClickListener(this);
        findViewById(R.id.iv_back).setOnClickListener(this);
        ivSwitch.setOnClickListener(this);
        btnCamera.setOnClickListener(this);
        tvToUse.setOnClickListener(this);
        ivFlashlight.setOnClickListener(this);
        viewVoiceFrom.setOnClickListener(this);
        viewVoiceTo.setOnClickListener(this);
        ivMenuCollect.setOnClickListener(this);
        copyLayout.setOnClickListener(this);
        shareLayout.setOnClickListener(this);
        tvRetry.setOnClickListener(this);

        //isDemoShow = PreferenceMgr.getInstance().getWordTransDemoStatus();
        isDemoShow = true;
        llDemo.setVisibility(isDemoShow?View.VISIBLE:View.GONE);
        tvOriginal.setMovementMethod(ScrollingMovementMethod.getInstance());
        tvTrans.setMovementMethod(ScrollingMovementMethod.getInstance());
    }

    private void createLensEngine() {
        if (this.lensEngine == null) {
            this.lensEngine = new LensEngine(this, this.cameraConfiguration, this.graphicOverlay);
            mHandler.post(new Runnable() {
                int count = 0;
                @Override
                public void run() {

                    if(viewCut.getWidth() == 0 && count < 50){
                        ++count;
                        mHandler.postDelayed(this,100);
                    }else {
                        //int windowHeight = view1.getHeight()+viewLeft.getHeight()+view2.getHeight();
                        int windowWidth = view1.getWidth();

                        float proportion = (float) cameraConfiguration.getPreviewHeight()/(float)windowWidth;

                        int leftPx = (int) (viewCut.getLeft() * proportion);
                        int topPx = (int) ((viewCut.getTop() - viewCut.getHeight()/2) * proportion);

                        int widthPx = (int) (viewCut.getWidth() * proportion);
                        int heightPx = (int) (viewCut.getHeight() * proportion);
                        FrameMetadata.CutFrame cutFrame = new FrameMetadata.CutFrame(leftPx, topPx, widthPx, heightPx);
                        lensEngine.setCutFrame(cutFrame);
                    }
                }
            });
        }
        try {
            this.wordTransactor = new WordTransactor(this.mHandler,this);
            this.lensEngine.setMachineLearningFrameTransactor(this.wordTransactor);
            isInitialization = true;

            WordTransResultCallBack wordTransResultCallBack = new WordTransResultCallBack();
            wordTransactor.addTextResultCallBack(wordTransResultCallBack);
        } catch (Exception e) {
            Toast.makeText(
                            this,
                            "Can not create image transactor: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                    .show();
        }
    }

    private void restartLensEngine(String type) {
        if (!TextUtils.isEmpty(this.codeType)&&this.codeType.equals(type)) {
            return;
        }
        this.codeType = type;
        this.lensEngine.release();
        this.createLensEngine();
        this.startLensEngine();
        if (this.lensEngine == null || this.lensEngine.getCamera() == null) {
            return;
        }
        Camera mCamera = this.lensEngine.getCamera();
        try {
            mCamera.setPreviewDisplay(this.preview.getSurfaceHolder());
        } catch (IOException e) {
            Log.d(TAG, "initViews IOException");
        }
    }

    private void initTransComponent(){
        //翻译插件
        mTranslateComponent = new HdTranslateComponent(this);
        getLifecycle().addObserver(mTranslateComponent);
        //Tts语音播报插件
        voicePlayUtil = VoicePlayUtil.getInstance();
    }

    private void startLensEngine() {
        if (this.lensEngine != null) {
            try {
                this.preview.start(this.lensEngine, false);
            } catch (IOException e) {
                this.lensEngine.release();
                this.lensEngine = null;
            }
        }
    }

    //选择语言弹框
    private void showSelectLanguageDialog() {
        /*languageDialog = SelectTransLanguageDialog.newInstance(mDataModel.getLanguageFrom().getValue(), mDataModel.getLanguageTo().getValue(), isFromPage, false, false)
                .setOnLanguageChangedListener((fromLanguage, toLanguage) -> {
                    mDataModel.setLanguageFrom(fromLanguage);
                    mDataModel.setLanguageTo(toLanguage);
                });
        languageDialog.show(getSupportFragmentManager(), "WordTransLateActivity");*/


        languageDialog = new LanguageDialog(
                Objects.requireNonNull(mDataModel.getLanguageFrom().getValue()),
                Objects.requireNonNull(mDataModel.getLanguageTo().getValue()),
                isFromPage, LanguageDialogType.WORD, LanguageDialogType.TO_TEXT);
        languageDialog.show(getSupportFragmentManager(),"LanguageDialog");
        languageDialog.setOnLanguageChangedListener((fromLanguage, toLanguage, selectedLanguage) -> {
            mDataModel.setLanguageFrom(fromLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansFromLanguage(fromLanguage.getName());
            mDataModel.setLanguageTo(toLanguage);
            PreferenceMgr.getInstance().getTranslatePreference().saveTansToLanguage(toLanguage.getName());
        });
    }

    /**
     * 当前状态改变
     */
    private void translateStateChanged(int translateState) {
        switch (translateState) {
            case Constants.TRANSLATE_NORMAL://未翻译
                break;
            case Constants.TRANSLATING://翻译中
                break;
            case Constants.TRANSLATED://已翻译
                break;
        }
    }

    /**
     * 更新ivSwitch图标状态
     */
    private void updateSwitchStatus(HuDunLanguage huDunLanguage){

        if(huDunLanguage.getSupportDiscern() == 1){//为识别语言
            ivSwitch.setImageResource(R.mipmap.icon_change);
            twoWay = true;
        }else {
            ivSwitch.setImageResource(R.mipmap.icon_trans_right);
            twoWay = false;
        }
    }

    /**
     * 更新收藏图标状态
     */
    private void updateCollectStatus(TranslateRecord record) {
        Drawable collectDrawable = ivMenuCollect.getCompoundDrawables()[1];
        //更新收藏状态
        if (record.getIsCollected()) {
            collectDrawable.setLevel(2);
        } else {
            collectDrawable.setLevel(1);
        }
        ivMenuCollect.setCompoundDrawables(null, collectDrawable, null, null);
    }

    /**
     * 闪光灯切换
     */
    private void changeLight() {
        int level = ivFlashlight.getDrawable().getLevel();
        level++;
        int maxLens = 3;
        if (level > maxLens) {
            level = 1;
        }
        switch (level) {
            case Constants.LIGHT_AUTO:
                CamParaUtil.turnAuto(this.lensEngine.getCamera());
                break;
            case Constants.LIGHT_ON:
                CamParaUtil.turnOn(this.lensEngine.getCamera());
                break;
            case Constants.LIGHT_OFF:
                CamParaUtil.turnoff(this.lensEngine.getCamera());
                break;
        }
        ivFlashlight.setImageLevel(level);
    }

    /**
     * --------------------------start---------------------------------
     */
    //还未把分享从sdk 抽取出来前的写法。暂时保留。  可自行封装。
    private ShareTextFileManager shareMG;
    private SimpleDateFormat mFormat;
    private String shareFileName() {
        if (null == mFormat)
            mFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return mFormat.format(new Date().getTime());
    }
    private void shareWord() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName() + ".doc", EnShareFileType.WORD_FILE);
    }
    private void shareTxt() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName(), EnShareFileType.TXT_FILE);
    }
    private void sharePdf() {
        shareMG.shareTextFile(StringUtils.template(originalText, translatedText), shareFileName() + ".pdf", EnShareFileType.PDF_FILE);
    }
    /**
     * --------------------------end---------------------------------
     */

    //是否绑定eventbus
    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    /**
     * eventbus 通知语音播放完成。
     *
     * @param event
     */
    @Override
    protected void onXEventRecv(HuDunEvent<?> event) {
        super.onXEventRecv(event);
        switch (event.getEventCode()) {
            case AppEvents.PLAY_COMPLETE: //播放器播放完成
                if (mCurrentViewVoice != null)
                    mCurrentViewVoice.stopPlay();
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!isInitialization){
            createLensEngine();
        }
        this.startLensEngine();
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopPlaying();
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.preview.stop();
    }

    private void releaseLensEngine() {
        if (this.lensEngine != null) {
            this.lensEngine.release();
            this.lensEngine = null;
        }
        //recycleBitmap();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wordTransactor.addTextResultCallBack(null);//规避了崩溃bug
        mHandler.removeCallbacksAndMessages(null);//规避了崩溃bug
        releaseLensEngine();//释放相机资源
        mDataModel.getTranslateState().removeObservers(this);
        mDataModel.getLanguageFrom().removeObservers(this);
        mDataModel.getLanguageTo().removeObservers(this);
        getLifecycle().removeObserver(mTranslateComponent);

        voicePlayUtil.destroy();
    }

    @Override
    public void onViewClick(View v) {
        int viewId = v.getId();
        if(viewId == R.id.btn_camera){
            if(isLocked){
                if(lensEngine != null){
                    lensEngine.startHandlePreviewFrame();
                }
                isLocked = false;
                lastTime = System.currentTimeMillis();
                tvStatusTips1.setVisibility(View.GONE);
                tvStatusTips2.setText("锁定\n单词");
                llResultPart.setVisibility(View.GONE);

                TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS, TrackerForTrans.CANCEL_LOCK_WORD);
            }else {
                if(llResultPart.getVisibility() == View.VISIBLE){
                    isLocked = true;
                    tvStatusTips1.setVisibility(View.VISIBLE);
                    tvStatusTips2.setText("取消\n锁定");
                    //埋点
                    TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS, TrackerForTrans.LOCK_WORD);
                }else {
                    ToastUtils.showNormal("您还没有取词");
                }
            }

        }else if(viewId == R.id.iv_back){
            finish();
        }else if(viewId == R.id.tv_retry){
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.RETRY);
            if(lensEngine != null){
                lensEngine.startHandlePreviewFrame();
            }
            isAllowPass = true;
            llResultNone.setVisibility(View.GONE);
            lastTime = System.currentTimeMillis();
        } else if(viewId == R.id.ly_from){
            isFromPage = true;
            showSelectLanguageDialog();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
        }else if(viewId == R.id.ly_to){
            isFromPage = false;
            showSelectLanguageDialog();
            mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
        }else if(viewId == R.id.iv_switch){
            if(twoWay){
                //视图交换动画
                showTranslateAnimation();
            }
        }else if(viewId == R.id.tv_to_use){
            if (isLimit4Use(EventCode.WORD_TRANS)) {
                //PreferenceMgr.getInstance().saveWordTransDemoStatus(false);
                if(lensEngine != null){
                    lensEngine.startHandlePreviewFrame();
                }
                llDemo.setVisibility(View.GONE);
                isDemoShow = false;
                lastTime = System.currentTimeMillis();
            }

        }else if(viewId == R.id.iv_flashlight){
            changeLight();
        }else if (viewId == R.id.view_voice_from) {
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.VOICE_PLAY);
            executeTtsPlay(viewVoiceFrom,false, EventCode.VOICE_PLAY_ORIGINAL);

        }else if (viewId == R.id.view_voice_to) {
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.VOICE_PLAY);
            executeTtsPlay(viewVoiceTo,true,EventCode.VOICE_PLAY_TRANS);

        }else if (viewId == R.id.iv_menu_collect) {//收藏
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.COLLECTION);
            if (translateRecord != null) {
                if (translateRecord.getIsCollected()) {
                    translateRecord.setIsCollected(false);
                    ToastUtils.showNormal(R.string.collection_cancel);
                } else {
                    translateRecord.setIsCollected(true);
                    ToastUtils.showSuccess(R.string.collection_success);
                }

                //重复数据。就删除前面的历史数据
                DataBaseMgr instance = DataBaseMgr.getInstance();
                instance.isContain(translateRecord);
                instance.addTranslateRecord(translateRecord);

                //更新record
                mDataModel.setOperateRecord(translateRecord);
            }
        }else if (viewId == R.id.copy_layout) {    //复制
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.COPY_TRANS_RESULT);
            if (isLimit4Use(EventCode.TEXT_COPY)) {
                ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                ClipData mClipData = ClipData.newPlainText("翻译结果", translatedText);
                cmb.setPrimaryClip(mClipData);
                ToastUtils.showNormal(getResources().getString(R.string.copy_success_tips));
                //Toast.makeText(this, "结果已复制", Toast.LENGTH_SHORT).show();
            }

        }else if (viewId == R.id.share_layout) {       //分享
            TranslationInterior.getTrackerListener().click(TrackerForTrans.WORD_TRANS,TrackerForTrans.SHARE);

            if (null != shareDialog) {
                shareDialog.show(getSupportFragmentManager(), "WordTransLateActivity");
            } else {
                ArrayList<ShareItemBean> item = new ArrayList();
                item.add(new ShareItemBean(R.mipmap.text_icon_share_word, getResources().getString(R.string.export_word)));
                item.add(new ShareItemBean(R.mipmap.text_icon_share_txt, getResources().getString(R.string.export_txt)));
                item.add(new ShareItemBean(R.mipmap.text_icon_share_pdf, getResources().getString(R.string.export_pdf)));
                shareDialog = ShareDialog.builder().setList(item)
                        .setButtonColor(TranslationInterior.getThemeColor())
                        .setItemClickListenner(new ShareDialog.OnShareItemClickListenner() {
                            @Override
                            public void OnItemClick(Dialog dialog, ShareResultAdapter adapter, int position) {
                                if (shareMG == null) {
                                    shareMG = new ShareTextFileManager(getActivity());
                                }
                                switch (position) {
                                    case 0: //导出Word
                                        if (isLimit4Use(EventCode.TEXT_SHARE_WORD)) {
                                            shareWord();
                                        }
                                        break;
                                    case 1://导出TXT
                                        if (isLimit4Use(EventCode.TEXT_SHARE_TXT)) {
                                            shareTxt();
                                        }
                                        break;
                                    case 2://导出PDF
                                        if (isLimit4Use(EventCode.TEXT_SHARE_PDF)) {
                                            sharePdf();
                                        }
                                        break;
                                }
                                dialog.dismiss();
                            }
                        }).build(false);
                shareDialog.show(getSupportFragmentManager(), "WordTransLateActivity");
            }
        }
    }

    /**
     * 互换语种动画
     */
    private void showTranslateAnimation() {
        if("自动检测".equals(mDataModel.getLanguageFrom().getValue().getName())){
            ToastUtils.showNormal(getResources().getString(R.string.tips_to_not_auto));
            return;
        }
        TranslateAnimation ta1 = new TranslateAnimation(0, lyFrom.getWidth() + ivSwitch.getWidth(), 0, 0);
        ta1.setDuration(600);
        ta1.setFillAfter(true);
        lyFrom.startAnimation(ta1);
        lyFrom.bringToFront();

        TranslateAnimation ta2 = new TranslateAnimation(0, -lyTo.getWidth()-ivSwitch.getWidth(), 0, 0);
        ta2.setDuration(600);
        ta2.setFillAfter(true);
        lyTo.startAnimation(ta2);
        lyTo.bringToFront();

        ta1.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                HuDunLanguage fromTemp = mDataModel.getLanguageFrom().getValue();
                mDataModel.setLanguageFrom(mDataModel.getLanguageTo().getValue());
                mDataModel.setLanguageTo(fromTemp);
                mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        ta2.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                animation.cancel();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void executeTtsPlay(VoicePlayView voicePlayView, boolean isTransPart, EventCode code){

        if (isLimit4Use(code)) {
            voicePlayback(voicePlayView,isTransPart);
        }
    }

    /**
     * 执行翻译  参考项目原有逻辑。
     */
    private void executeTranslate(String origContent) {
        if(isTranslating) return;
        if (TextUtils.isEmpty(origContent))
            return;
        if(mDataModel.getLanguageTo().getValue() == null
                || mDataModel.getLanguageFrom().getValue() == null){
            return;
        }
        //如果最后请求原文和最后请求目标语言都一致则不请求接口，从历史数据获取并展示
        if (origContent.equals(originalText) && mDataModel.getLanguageTo().getValue().getTranslateCode().equals(lastTransCode)
                && mDataModel.getLanguageFrom().getValue().getTranslateCode().equals(lastOriginalCode)) {
            return;
        }
        //显示原文内容
        tvOriginal.setText(origContent);
        //隐藏翻译文本布局
        rlTransPart.setVisibility(View.GONE);

        //记录下最后请求的目标语言
        lastTransCode = this.mDataModel.getLanguageTo().getValue().getTranslateCode();
        lastOriginalCode = this.mDataModel.getLanguageFrom().getValue().getTranslateCode();
        showLoadDialog("翻译中...");
        isTranslating = true;
        mTranslateComponent.translationText(this,origContent,
                this.mDataModel.getLanguageFrom().getValue().getTranslateCode(),
                this.mDataModel.getLanguageTo().getValue().getTranslateCode(),
                PreferenceMgr.getInstance().isOpenOfflineTrans(),
                new TranslateCallback() {
                    @Override
                    public void onTranslateFailed(int code, String msg) {
                        originalText = "";
                        hideLoadDialog();
                        isTranslating = false;
                        WordTranslateActivity.this.mDataModel.setTranslateState(Constants.TRANSLATE_NORMAL);
                        if(code == Constants.ResponseCode.ERROR_IS_DANGER
                                || code == Constants.ResponseCode.ERROR_COMM){
                            ToastUtils.showError(msg);
                        }else {
                            ToastUtils.showError(R.string.fanyi_faith_tip);
                        }
                    }

                    @Override
                    public void onTranslateCompleted(
                            String data,
                            String fromLangCode,
                            String toLangCode,
                            boolean status) {
                        //记录下最后请求的原文
                        originalText = origContent;
                        translatedText = data;
                        hideLoadDialog();
                        isTranslating = false;
                        WordTranslateActivity.this.mDataModel.setTranslateState(Constants.TRANSLATED);

                        TranslateRecord record = new TranslateRecord();
                        record.setIsVoice(false);
                        record.setIsNation(false);
                        record.setIsCollected(false);
                        record.setLanguageFrom(WordTranslateActivity.this.mDataModel.getLanguageFrom().getValue());
                        record.setLanguageTo(WordTranslateActivity.this.mDataModel.getLanguageTo().getValue());
                        record.setContentOrig(origContent);
                        record.setContentTranslate(data);
                        record.setTriggerTime(System.currentTimeMillis());

                        mDataModel.setOperateRecord(record);
                        success();
                    }
                });
    }

    private void stopPlaying() {
        if(mCurrentViewVoice != null && mCurrentViewVoice.isPlaying()){
            mCurrentViewVoice.stopPlay();
        }
        voicePlayUtil.stopPlay();
    }


    /**
     * 语音播报
     */
    private void voicePlayback(VoicePlayView mVoicePlayView, boolean isTransPart){
        /*mCurrentViewVoice = voicePlayUtil
                            .executeTtsPlay(voicePlayView,mCurrentViewVoice,translateRecord,isTransPart);*/

        if(voicePlayUtil.isPlaying()){
            voicePlayUtil.stopPlay();
        }
        if(mCurrentViewVoice != null){
            mCurrentViewVoice.loadingComplete();
            if(mCurrentViewVoice.isPlaying()){
                mCurrentViewVoice.stopPlay();
                if(mCurrentViewVoice == mVoicePlayView)
                    return;
            }
        }
        mCurrentViewVoice = mVoicePlayView;

        if(translateRecord == null
                || translateRecord.getLanguageFrom() == null
                || translateRecord.getLanguageTo() == null
                || TextUtils.isEmpty(translateRecord.getContentTranslate())
                || TextUtils.isEmpty(translateRecord.getContentOrig())){
            return;
        }

        String content = isTransPart?translateRecord.getContentTranslate():translateRecord.getContentOrig();
        String ttsCode;
        if(isTransPart){
            ttsCode = translateRecord.getIsReverse() ? translateRecord.getLanguageFrom().getTtsCode() : translateRecord.getLanguageTo().getTtsCode();
        }else {
            ttsCode = translateRecord.getIsReverse() ? translateRecord.getLanguageTo().getTtsCode() : translateRecord.getLanguageFrom().getTtsCode();
        }
        voicePlayUtil.executeCompositeFile(ttsCode, content, new VoiceComposeListener() {
            @Override
            public void onStarting() {

                mCurrentViewVoice.loading();
            }

            @Override
            public void onCompleted(String file, boolean isLocal) {
                mCurrentViewVoice.startPlay();
                voicePlayUtil.startPlay(file);
            }

            @Override
            public void onDownloadFailed() {
                mCurrentViewVoice.loadingFailed();
                voicePlayUtil.stopPlay();
            }
        });
    }

    private boolean isLimit4Use(EventCode code) {
        return !intercept(code);
    }

    private void success() {
        consumeFreeTrial();
    }

    class WordTransResultCallBack implements WordTransactor.ResultCallBack {

        @Override
        public void onSuccessForText(Bitmap originalCameraImage, MLText text, GraphicOverlay graphicOverlay) {
            if(isDemoShow || isLocked || !isAllowPass){
                if(lensEngine != null){
                    lensEngine.pauseHandlePreviewFrame();
                }
                return;
            }

            if(languageDialog != null
                    && languageDialog.getDialog() != null
                    && languageDialog.getDialog().isShowing()){
                return;
            }

            String origContent = text.getStringValue().trim();
            if(TextUtils.isEmpty(origContent)){
                return;
            }

            if(CheckDoubleClick.isIntervalClick(DELAY_MS)){
                //开始翻译
                if(isLimit4Use(EventCode.WORD_TRANS)){
                    executeTranslate(origContent);
                    mHandler.sendEmptyMessage(Constant.SHOW_TAKE_PHOTO_BUTTON);
                    lastTime = System.currentTimeMillis();
                }else {
                    mHandler.sendEmptyMessage(Constant.HIDE_TAKE_PHOTO_BUTTON);
                }
            }

        }

        @Override
        public void onFailureForText() {
            if(isDemoShow || isLocked || !isAllowPass){
                return;
            }
            long currentTime = System.currentTimeMillis();
            if((currentTime - lastTime) > 2*DELAY_MS){

                mHandler.sendEmptyMessage(Constant.HIDE_TAKE_PHOTO_BUTTON);
            }
        }

    }
}
